package net.jeeshop.core.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import sun.util.logging.resources.logging;

import freemarker.template.utility.StringUtil;

public class HttpUtil {
	private static final String default_charset = "utf-8";
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	public static String get(String url0,String data,String charset) throws IOException {
		if(StringUtils.isBlank(charset)){
			charset = default_charset;
		}
		/**
		 * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如： // Using
		 * java.net.URL and //java.net.URLConnection
		 */
		URL url = new URL(url0);
		URLConnection conn = url.openConnection();
		/**
		 * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。
		 * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做：
		 */
		conn.setDoOutput(true);
		
		//当存在post的值时，才打开OutputStreamWriter  
        if(data!=null && data.toString().trim().length()>0){  
        	/**
    		 * 最后，为了得到OutputStream，简单起见，把它约束在Writer并且放入POST信息中，例如： ...
    		 */
    		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),charset);
    		out.write("username=kevin&password=*********"); // post的关键所在！
    		// remember to clean up
    		out.flush();
    		out.close();
        }
        
		/**
		 * 这样就可以发送一个看起来象这样的POST： POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
		 * text/plain Content-type: application/x-www-form-urlencoded
		 * Content-length: 99 username=bob password=someword
		 */
		// 一旦发送成功，用以下方法就可以得到服务器的回应：
		String sCurrentLine = null;
		StringBuilder buff = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),charset));
		while ((sCurrentLine = reader.readLine()) != null) {
//			buff.append(new String(sCurrentLine.getBytes(), charset));
			logger.error("sCurrentLine="+sCurrentLine);
			buff.append(sCurrentLine);
		}
		return buff.toString();
	}
	
	
	public static String postJson(String json, String url,String encode)
			throws ClientProtocolException, IOException {

				logger.info("httpclient执行新闻资讯接口开始。");
				DefaultHttpClient httpClient = new DefaultHttpClient();

				HttpPost method = new HttpPost(url);
				StringEntity entity = new StringEntity(json,encode);//解决中文乱码问题  
				entity.setContentEncoding(encode);  
				entity.setContentType("application/json");  
				method.setEntity(entity);  
				
				//这边使用适用正常的表单提交 

//				 List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();  
				//pairList.add(new BasicNameValuePair("chnl_id", "11")); 
				//pairList.add(new BasicNameValuePair("title", bean.getTitle()));// 标题  
				//pairList.add(new BasicNameValuePair("content", bean.getContent()));// 资讯内容  
				//pairList.add(new BasicNameValuePair("source_url", bean.getSourceUrl()));// 资讯源地址  
				//pairList.add(new BasicNameValuePair("source_name", bean.getSourceFrom()));// 来源网站名称  
				//pairList.add(new BasicNameValuePair("img_urls", bean.getImgUrls()));// 采用 url,url,url 的格式进行图片的返回  
				//method.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); 
				
	            
				HttpResponse httpResponse = httpClient.execute(method);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					// 请求结束，返回结果
					return EntityUtils.toString(httpResponse.getEntity(),encode);
				}
				return "";

		}
	
	
	
	
	//用apache接口实现http的post提交数据
		public static String sendHttpClientPost(String path,
				Map<String, String> params, String encode) {

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					list.add(new BasicNameValuePair(entry.getKey(), entry
							.getValue()));
				}
			}

			try {
				// 实现将请求的参数封装到表单中，即请求体中
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
				// 使用post方式提交数据
				HttpPost httpPost = new HttpPost(path);
				httpPost.setEntity(entity);
		// 执行post请求，并获取服务器端的响应HttpResponse
				DefaultHttpClient client = new DefaultHttpClient();
				HttpResponse httpResponse = client.execute(httpPost);
				
				//获取服务器端返回的状态码和输入流，将输入流转换成字符串
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					InputStream inputStream = httpResponse.getEntity().getContent();
					return changeInputStream(inputStream, encode);
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return "";

		}

		/*
		 * // 把从输入流InputStream按指定编码格式encode变成字符串String
		 */
		public static String changeInputStream(InputStream inputStream,
				String encode) {

			// ByteArrayOutputStream 一般叫做内存流
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			byte[] data = new byte[1024*10];
			int len = 0;
			String result = "";
			if (inputStream != null) {

				try {
					while ((len = inputStream.read(data)) != -1) {
						byteArrayOutputStream.write(data, 0, len);

					}
					result = new String(byteArrayOutputStream.toByteArray(), encode);

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			return result;
		}
	
	
	/**
	 * 上传文件
	 * @param httpUrl：可带参数的服务器请求地址
	 * @param filePath：文件的路径
	 * @return
	 */
	public static String upload(String httpUrl, File file) {
		String strResutl = null;
		HttpPost httpPost = new HttpPost(httpUrl);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response;

		try {
            FileBody bin = new FileBody(file);  
            MultipartEntity reqEntity = new MultipartEntity();  
            reqEntity.addPart("file", bin);//file1为请求后台的File upload;属性      
			
			httpPost.setEntity(reqEntity);
			response = httpClient.execute(httpPost);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				strResutl = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return strResutl;
	}

	

	public static void main(String[] args) throws IOException {
		//System.out.println(HttpUtil.get("http://www.baidu.com",null,"UTF-8"));
		
		/**
		 * 
{
    "type":"1",
    "no":"18287113237",
    "memberCode":"18502818214",
    "payAmount": "0.01"
}
		 */
		String path = "http://sch.expopay.cn/center/phone/order?token=bvq8e8j39e1z106nqzx1jad2q";
		Map<String, String> params = new HashMap<String, String>();
		params.put("type", "8");
		params.put("no", "123");
		params.put("memberCode", "123");
		params.put("payAmount", "0.01");
//		String result = sendHttpClientPost(path, params, "utf-8");
		String result =postJson(JSON.toJSONString(params), path,"utf-8");
		System.out.println("-result->>" + result);
		
		
	}
}
